<!-- 添加/修改采购订单 -->
<template>
  <div class="purchase_batch_insert_phone">
    <el-card>
      <Table
        :data="tableData"
        :misStripe="true"
        :row-style="rowStyle">
        <el-table-column
          label="编号-类型"
          :resizable="false">
          <template #default="scope">
            {{ scope.$index + 1 }} - {{ purchaseNodeType[scope.row.nodeTypeEnum] }}
          </template>
        </el-table-column>
        <el-table-column
          label="简称"
          :resizable="false">
          <template #default="scope">
            <el-select
              v-model="scope.row.nodeRelationId"
              v-if="scope.row.nodeTypeEnum === Object.keys(purchaseNodeType)[0]"
              placeholder="简称"
              clearable
              @change="(val) => changeRiceBarnEvent(val, scope.row)">
              <el-option
                v-for="item in riceBarnList"
                :key="item.id"
                :disabled="item.disabled"
                :label="item.simple_name"
                :value="item.id" />
            </el-select>
            <span v-else>{{ scope.row.nodeRelationName }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="付款方式"
          :resizable="false">
          <template #default="scope">
            <span v-if="scope.row.capitalFirstPayWayEnum">{{ FirstPayWay.find(item => item.value ===
              scope.row.capitalFirstPayWayEnum).label }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="120"
          :resizable="false">
          <template #default="scope">
            <el-link
              v-if="!route.query.purchaseOrderNumber && scope.row.nodeTypeEnum === Object.keys(purchaseNodeType)[0]"
              style="margin-right: 10px;"
              :underline="false"
              type="info"
              @click.stop="addLinkEvent(scope.row)">
              新增链路
            </el-link>
            <el-link
              v-if="scope.row.nodeTypeEnum !== Object.keys(purchaseNodeType)[0]"
              :underline="false"
              type="warning"
              @click.stop="editEvent(scope.row)">
              {{ config.button.text.edit }}
            </el-link>
            <el-link
              v-if="!route.query.purchaseOrderNumber && scope.row.nodeTypeEnum === Object.keys(purchaseNodeType)[3] || !route.query.purchaseOrderNumber && scope.row.nodeTypeEnum === Object.keys(purchaseNodeType)[4]"
              style="margin-left: 10px;"
              :underline="false"
              type="danger"
              @click.stop="deleteEvent(scope.$index)">
              {{ config.button.text.delete }}
            </el-link>
          </template>
        </el-table-column>
      </Table>

      <el-divider content-position="left">采购订单信息</el-divider>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-width="config.form.label.width"
        status-icon>
        <el-row>
          <el-col
            :span="8"
            class="el_col_fit">
            <el-form-item
              label="资金仓库"
              prop="baseCapitalWarehouseId">
              <el-select
                v-model="formData.baseCapitalWarehouseId"
                @change="capitalWareHouseChange"
                placeholder="资金仓库"
                clearable>
                <el-option
                  v-for="item in capitalWareHouseList"
                  :key="item.id"
                  :disabled="item.disabled"
                  :label="item.name"
                  :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            class="el_col_fit">
            <el-form-item
              label="采购总吨数(吨)"
              prop="purchaseSumTon">
              <el-input-number
                v-model="formData.purchaseSumTon"
                controls-position="right"
                :min="0"
                :precision="3">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            class="el_col_fit">
            <el-form-item
              label="基础提货单价(元/吨)"
              prop="basePickUnitPrice">
              <el-input-number
                v-model="formData.basePickUnitPrice"
                controls-position="right"
                :min="0"
                :precision="2">
              </el-input-number>
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            class="el_col_fit">
            <el-form-item
              label="采购日期"
              prop="purchaseDate">
              <el-date-picker
                v-model="formData.purchaseDate"
                style="width: 100%;"
                type="date"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                placeholder="采购日期" />
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            class="el_col_fit">
            <el-form-item
              label="采购订单编号"
              prop="purchaseOrderNumber">
              <el-input
                v-model="formData.purchaseOrderNumber"
                placeholder="采购订单编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            class="el_col_fit purchase_order_name">
            <el-form-item
              label="采购订单名称"
              prop="purchaseOrderName">
              <el-input
                v-model="formData.purchaseOrderName"
                placeholder="采购订单名称"></el-input>
              <el-tooltip
                class="box-item"
                effect="dark"
                content="点击赋值米厂名称+编号"
                placement="top">
                <el-icon
                  size="20"
                  style="cursor: pointer;"
                  @click="assign">
                  <QuestionFilled />
                </el-icon>
              </el-tooltip>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="number">
          <el-col
            :span="8"
            class="el_col_fit">
            <el-form-item
              label="启用状态"
              prop="isEnable">
              <el-select
                v-model="formData.isEnable"
                placeholder="启用状态"
                clearable>
                <el-option
                  :label="config.button.text.enable"
                  :value="true" />
                <el-option
                  :label="config.button.text.stop"
                  :value="false" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col
            :span="8"
            class="el_col_fit">
            <el-form-item
              label="编号"
              prop="serialNumber">
              <el-input-number
                v-model="formData.serialNumber"
                style="width: 100px;"
                controls-position="right"
                :min="maxNumber ? maxNumber + 1 : 1">
              </el-input-number>
              <el-alert
                type="warning"
                size="small"
                :closable="false">
                <template #title>
                  当前最大编号：{{ maxNumber }}
                </template>
              </el-alert>
            </el-form-item>
          </el-col>
          <el-col
            :span="4"
            class="el_col_fit">
            <el-form-item
              label="是否填写完成"
              prop="isWriteSuccess">
              <el-switch
                v-model="formData.isWriteSuccess"
                class="ml-2"
                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949" />
            </el-form-item>
          </el-col>
          <el-col
            :span="24"
            class="el_col_fit">
            <el-form-item
              label="附件"
              prop="fileDataJson">
              <UploadFile
                ref="uploadRef"
                :show="true"
                :file-uuids="fileDataList"
                @success="success"
                @delete-file="deleteFile" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 8px;">
          <el-button
            style="width: 100%;"
            @click="router.back()">
            {{ config.button.text.close }}
          </el-button>
        </el-row>
        <el-row>
          <el-button
            v-if="!route.query.purchaseOrderNumber"
            style="width: 100%;"
            type="info"
            :disabled="!isClickAdd"
            @click="addEvent">
            {{ config.button.text.add }}
          </el-button>
          <el-button
            v-else
            style="width: 100%;"
            type="warning"
            @click="editSaveEvent">
            {{ config.button.text.edit }}
          </el-button>
        </el-row>
      </el-form>
    </el-card>

    <!-- 添加链路 -->
    <AddLink
      ref="addLinkRef"
      @save-link="saveLink" />
    <!-- 修改 -->
    <OrderInfo
      ref="orderInfoRef"
      :rowData="rowData"
      :quoteInfo="quoteInfo"
      @save="save" />
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from "vue";
import ApiPurchaseOrder from "@/api/modules/purchase-order"
import config from "@/common/element-plus/config";
import ApiCapitalWareHouse from "@/api/modules/capital-ware-house"
import AddLink from "./component/AddLink.vue"
import OrderInfo from "./component/OrderInfo.vue"
import Table from "@/components/Table.vue"
import { useRoute, useRouter } from "vue-router"
import { useValidator } from "@/hooks/useValidator";
import message from "@/common/element-plus/message";
import { purchaseNodeType, FirstPayWay } from "@/common/enum/purchase-order";
import confirm from "@/common/element-plus/confirm";
import ApiPurchaseOrderNode from "@/api/modules/purchase-order-node"
import ApiBaseRiceBarn from "@/api/modules/base-rice-barn"
import UploadFile from "@/components/UploadFile.vue"

// 路由
const route = useRoute()
const router = useRouter()
// 资金仓库简称列表
const capitalWareHouseList = ref([])
// 米厂简称列表
const riceBarnList = ref([])
// 附件回显
const fileDataList = ref([]);
// 主表
const formData = ref({})
// 新增链路实例
const addLinkRef = ref()
// 修改组件实例
const orderInfoRef = ref()
// 每行数据
const rowData = ref({})
// 表格
const tableData = ref([])
// 最大编号
const maxNumber = ref("")
// 仓储费/比率是否引用
const quoteInfo = ref({
  isQuote: false,
  baseCapitalWarehouseId: "",
})
// 新增按钮是否能点击
const isClickAdd = ref(false)
const { required, validate } = useValidator()
const formRef = ref()
const formRules = {
  baseCapitalWarehouseId: [required("资金仓库", "change")],
  purchaseSumTon: [required("采购总吨数")],
  basePickUnitPrice: [required("基础提货单价")],
  purchaseDate: [required("采购日期", "change")],
  purchaseOrderNumber: [required("采购订单编号")],
  purchaseOrderName: [required("采购订单名称")],
  serialNumber: [required("编号")],
  isEnable: [required("启用状态", "change")],
}

const nodeList = {
  purchaseOrderNumber: "",
  billNumber: "",
  nodeUnitPrice: "",
  capitalFirstPayWayEnum: "",
  capitalFirstPayPercent: "",
  capitalEndPayPercent: "",
  companyFirstPayPercent: "",
  dailyChemicalRate: "",
  baseCapitalWarehouseCostRuleName: "",
  storageChargeFee: "",
  isTimeSection: false,
  sectionRuleJson: "[]",
  nodeTypeEnum: "",
  nodeRelationId: "",
  nodeUuid: "",
  nodePuuid: "",
  fileDataJson: "[]",
  companyPaidFirstPrice: ""
}

// 新增保存
const addEvent = async () => {
  await validate(formRef.value)
  const data = await confirm.submit()
  if (data !== "confirm") return
  tableData.value.forEach(item => {
    item.baseCapitalWarehouseCostRuleName = item.name
  })
  await ApiPurchaseOrder.insertPurchaseOrder({
    purchaseOrder: {
      ...formData.value,
      // isWriteSuccess: true,
    },
    purchaseOrderNode: tableData.value
  })
  message.success()
}

// 修改保存
const editSaveEvent = async () => {
  await validate(formRef.value)
  const data = await confirm.submit()
  if (data !== "confirm") return
  await ApiPurchaseOrder.update(formData.value)
  message.success()
}

// 打开新增链路对话框
const addLinkEvent = (row) => {
  if (route.query.purchaseOrderNumber) return
  if (row.nodeTypeEnum === Object.keys(purchaseNodeType)[0]) {
    addLinkRef.value.visibility = true
  }
}

// 删除
const deleteEvent = (index) => {
  confirm.delete().then(data => {
    if (data === "confirm") {
      tableData.value.splice(index, 1)
      message.success()
    }
  })
}

// 采购订单名称赋值
const assign = () => {
  riceBarnList.value.forEach(item => {
    if (item.id === tableData.value[0].nodeRelationId) {
      formData.value.purchaseOrderName = item.simple_name + formData.value.serialNumber
    }
  })
}

// 资金仓库选择更改
const capitalWareHouseChange = () => {
  quoteInfo.value.baseCapitalWarehouseId = formData.value.baseCapitalWarehouseId
  if (formData.value.baseCapitalWarehouseId) {
    quoteInfo.value.isQuote = true
  } else {
    quoteInfo.value.isQuote = false
  }
}

const change = async () => {
  const filter = tableData.value.filter(item => item.nodeTypeEnum === Object.keys(purchaseNodeType)[0] || item.nodeTypeEnum === Object.keys(purchaseNodeType)[1] || item.nodeTypeEnum === Object.keys(purchaseNodeType)[2])
  const val = filter.every(item => item.nodeRelationId)
  if (val) {
    formData.value.baseRiceBarnId = tableData.value.find(item => item.nodeTypeEnum === Object.keys(purchaseNodeType)[0]).nodeRelationId
    formData.value.baseCapitalPartyId = tableData.value.find(item => item.nodeTypeEnum === Object.keys(purchaseNodeType)[1]).nodeRelationId
    formData.value.baseCompanyId = tableData.value.find(item => item.nodeTypeEnum === Object.keys(purchaseNodeType)[2]).nodeRelationId
    await getMaxUsedSerialNumber(true)
  }
}

const changeRiceBarnEvent = (val, row) => {
  nextTick(async () => {
    if (route.query.purchaseOrderNumber && val) {
      await ApiPurchaseOrderNode.update(row)
    }
  })
}

// 最大已使用编号
const getMaxUsedSerialNumber = async (val) => {
  const data = await ApiPurchaseOrder.getMaxUsedSerialNumber({
    riceBarnId: formData.value.baseRiceBarnId,
    baseCapitalPartyId: formData.value.baseCapitalPartyId,
    baseCompanyId: formData.value.baseCompanyId,
  })
  maxNumber.value = data.data
  if (val) {
    formData.value.serialNumber = data.data + 1
    isClickAdd.value = true
  } else {
    formData.value.serialNumber = data.data
  }
}

// 更改行背景色
const rowStyle = ({ row }) => {
  if (row.nodeTypeEnum.startsWith("BASE_")) {
    return { backgroundColor: "#f4fdee" }
  }
  return { backgroundColor: "#d9ddd9" };
}

// 修改
const editEvent = (row) => {
  orderInfoRef.value.visibility = true
  rowData.value = Object.assign({}, row)
}
const save = async (data) => {
  const findIndex = tableData.value.findIndex(item => item.nodeTypeEnum === data.nodeTypeEnum)
  tableData.value[findIndex] = data
  if (!route.query.purchaseOrderNumber) {
    await change()
  }
  message.success()
}

// 上传文件成功回调
const success = (data) => {
  const file = formData.value.fileDataJson ? JSON.parse(formData.value.fileDataJson) : []
  file.push(data)
  formData.value.fileDataJson = JSON.stringify(file)
}

// 删除文件回调
const deleteFile = (data) => {
  const file = JSON.parse(formData.value.fileDataJson)
  formData.value.fileDataJson = JSON.stringify(file.filter(item => item === data))
}

// 新增链路
const saveLink = (data) => {
  tableData.value.splice(1, 0, {
    ...nodeList,
    nodeTypeEnum: data
  })
}

onMounted(async () => {
    // 资金仓库简称列表
    let data = await ApiCapitalWareHouse.getSimpleNameList("/baseCapitalWarehouse/")
  capitalWareHouseList.value = data.data
  // 米厂简称列表
  data = await ApiBaseRiceBarn.getSimpleNameList()
  riceBarnList.value = data.data
  tableData.value = []
  formData.value = {}
  for (let index = 0; index <= 2; index++) {
    tableData.value.push({
      ...nodeList,
      nodeTypeEnum: Object.keys(purchaseNodeType)[index]
    })
  }
  setTimeout(async () => {
    if (route.query.purchaseOrderNumber) {
      // 节点列表信息
      let data = await ApiPurchaseOrderNode.getListNodeByPurchaseOrderNumber({
        purchaseOrderNumber: route.query.purchaseOrderNumber
      })
      tableData.value = data.data
      tableData.value.forEach(item => {
        item.name = item.baseCapitalWarehouseCostRuleName
      })
      const findT = riceBarnList.value.find(item => item.id === tableData.value[0].nodeRelationId)
      if (!findT) riceBarnList.value.push({
        simple_name: tableData.value[0].nodeRelationName + "(已禁用)",
        id: tableData.value[0].nodeRelationId,
        disabled: true
      })
      data = await ApiPurchaseOrder.queryInfoByPurchaseOrderNumber({
        purchaseOrderNumber: route.query.purchaseOrderNumber
      })
      formData.value = data.data
      const find = capitalWareHouseList.value.find(item => item.id === formData.value.baseCapitalWarehouseId)
      if (!find) capitalWareHouseList.value.push({
        name: formData.value.baseCapitalWarehouseName + "(已禁用)",
        id: formData.value.baseCapitalWarehouseId,
        disabled: true
      })
      fileDataList.value = []
      if (formData.value.fileDataJson && Array.isArray(JSON.parse(formData.value.fileDataJson))) {
        fileDataList.value = JSON.parse(formData.value.fileDataJson);
      }
      capitalWareHouseChange()
      await getMaxUsedSerialNumber(false)
    } else {
      formData.value.isEnable = true
      formData.value.isWriteSuccess = false
    }
  }, 200)
})
</script>

<style lang="scss" scoped>
.purchase_batch_insert_phone {
  .el-card {
    height: calc(100vh - 90px);
  }

  .number {
    align-items: flex-start;

    .el-alert {
      width: auto;
      padding: 5px;
    }
  }

  .purchase_order_name {
    :deep(.el-form-item__content) {
      flex-wrap: nowrap;
    }
  }
}
</style>